package com.alibaba.citrus.ots.b2b.trade.order.facade.service;

import com.alibaba.acm.shaded.com.aliyuncs.utils.StringUtils;
import com.alibaba.citrus.ots.b2b.trade.order.functions.order.entity.OrderWriteEntity;
import com.alibaba.citrus.ots.b2b.trade.order.functions.order.factory.OrderWriteFactory;
import com.alibaba.citrus.ots.b2b.trade.order.functions.orderLine.entity.OrderLineWriteEntity;
import com.alibaba.citrus.ots.b2b.trade.order.functions.orderLine.factory.OrderLineWriteFactory;
import com.alibaba.citrus.ots.b2b.trade.order.functions.utils.SaveOrderConverter;
import com.alibaba.citrus.ots.b2b.trade.order.repository.OrderQueryRepository;
import com.alibaba.citrus.ots.common.annotation.EpochTransactional;
import com.alibaba.citrus.ots.common.annotation.ProcessInvoker;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.otsb2btradecenter.api.sandoutgoods.service.SandOutGoodsService;
import com.epoch.app.otsb2btradecenter.dto.request.OrderQueryRequest;
import com.epoch.app.otsb2btradecenter.dto.request.SendOutGoodsRequest;
import com.epoch.app.otsb2btradecenter.dto.response.DeliveryOrderModifyResponse;
import com.epoch.app.otsb2btradecenter.dto.response.OrderQueryResponse;
import com.epoch.app.otsb2btradecenter.sdo.OrderSDO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


@Service("sandOutGoodsService")
public class SandOutGoodsServiceImpl implements SandOutGoodsService {


    private Log log = Log.getLogger(SandOutGoodsServiceImpl.class);

    @Resource
    private OrderQueryRepository orderQueryRepository;

    @Override
    @ProcessInvoker
    @EpochTransactional(appCode="ots_b2b_trade_center", dataSourceCode = "cr_ots", dataSourceType = "app")
    public Result<DeliveryOrderModifyResponse> sandOutGoods(SendOutGoodsRequest request) {

        log.info("SendOutGoodsRequest request" + JSONObject.toJSONString(request));
        if (StringUtils.isEmpty(request.getOutMaterialCertificateId())) {
            return Result.fail("OTS-05-001-10-16-043","物料凭证单号不能为空");
        }

        if (!StringUtils.isEmpty(request.getOrderId())) {
            OrderQueryRequest orderQueryRequest = new OrderQueryRequest();
            orderQueryRequest.setId(request.getOrderId());
            OrderQueryResponse orderQueryResponse = orderQueryRepository.query(orderQueryRequest);
            if (Objects.isNull(orderQueryResponse)) {
                return Result.fail("OTS-05-001-10-16-036","销售订单不存在");
            }
            if (StringUtils.isNotEmpty(orderQueryResponse.getFeatures())) {
                Map<String, String> map = JSONObject.parseObject(orderQueryResponse.getFeatures(), new TypeReference<Map<String, String>>() {
                });
                if (request.getOutMaterialCertificateId().equals(map.get("outMaterialCertificateId"))) {
                    log.info(request.getOutMaterialCertificateId() + " 该物料凭证不能重复使用");
                    return Result.success(null);
                }
            }
            OrderSDO orderSDO = SaveOrderConverter.respConverterSDO(orderQueryResponse);
            if (MapUtils.isEmpty(orderSDO.getFeatures())) {
                orderSDO.setFeatures(new HashMap<>());
            }
            orderSDO.getFeatures().put("outMaterialCertificateId", request.getOutMaterialCertificateId());
            List<OrderLineWriteEntity> orderLineWriteEntities = OrderLineWriteFactory.modifyStatus(request,orderSDO);
            orderLineWriteEntities.forEach(OrderLineWriteEntity::modifyStatus);

            OrderWriteEntity orderWriteEntity = OrderWriteFactory.modifyStatus(orderSDO);
            orderWriteEntity.modifyStatus();

            return Result.success(new DeliveryOrderModifyResponse());
        }
        return Result.fail("OTS-05-001-10-16-026","销售订单不能为空");



        //TODO 后期处理
//        DeliveryOrderWriteEntity deliveryOrderWriteEntity = DeliveryOrderWriteFactory.modifyStatus(request , goodsAndOrderDetailDTOMap);
//        deliveryOrderWriteEntity.modify();


        //TODO 添加save方法
//        DeliveryOrderDetailEntity deliveryOrderDetailEntity = DeliveryOrderDetailFactory.modifyStatus(request);
//        deliveryOrderDetailEntity.modify();

        //            List<OrderLineWriteEntity> orderLineWriteEntities = OrderLineWriteFactory.modifyStatus(request,goodsAndOrderDetailDTOMap);
//            orderLineWriteEntities.stream().forEach(OrderLineWriteEntity::modifyStatus);

    }

    @Override
    @ProcessInvoker
    @EpochTransactional(appCode="ots_b2b_trade_center", dataSourceCode = "cr_ots", dataSourceType = "app")
    public Result<DeliveryOrderModifyResponse> chargeAgainstGoods(SendOutGoodsRequest request) {
        log.info("冲销请求入参:" + JSONObject.toJSONString(request));
        String outMaterialCertificateId = request.getOutMaterialCertificateId();
        if (StringUtils.isEmpty(outMaterialCertificateId)) {
            return Result.fail("","冲销物料凭证单号不能为空");
        }

        String orderId = request.getOrderId();
        if (StringUtils.isNotEmpty(orderId)) {
            //查询订单
            OrderQueryRequest orderQueryRequest = new OrderQueryRequest();
            orderQueryRequest.setId(request.getOrderId());
            OrderQueryResponse orderQueryResponse = orderQueryRepository.query(orderQueryRequest);

            //校验订单
            if (Objects.isNull(orderQueryResponse)) {
                return Result.fail("OTS-05-001-10-16-026","销售订单"+orderId+"不存在");
            }
            if (StringUtils.isNotEmpty(orderQueryResponse.getFeatures())) {
                Map<String, String> map = JSON.parseObject(orderQueryResponse.getFeatures(),HashMap.class);
                String chargeMaterialCertificateId = map.get("chargeMaterialCertificateId");
                if (outMaterialCertificateId.equals(chargeMaterialCertificateId)) {
                    log.info("销售订单"+orderId+"已冲销,物料凭证编号"+outMaterialCertificateId);
                    return Result.success(null);
                }
            }

            //更新订单
            OrderSDO orderSDO = SaveOrderConverter.respConverterSDO(orderQueryResponse);
            if (MapUtils.isEmpty(orderSDO.getFeatures())) {
                orderSDO.setFeatures(new HashMap<>());
            }
            orderSDO.getFeatures().put("chargeMaterialCertificateId",outMaterialCertificateId);

            List<OrderLineWriteEntity> orderLineWriteEntities = OrderLineWriteFactory.chargeAgainstStatus(request,orderSDO);
            if (CollectionUtils.isEmpty(orderLineWriteEntities)) {
                return Result.success(new DeliveryOrderModifyResponse());
            }
            orderLineWriteEntities.stream().forEach(OrderLineWriteEntity::modifyStatus);

            OrderWriteEntity orderWriteEntity = OrderWriteFactory.modifyChargeAgainstStatus(orderSDO);
            orderWriteEntity.modifyStatus();

            return Result.success(new DeliveryOrderModifyResponse());
        }

        return Result.fail("","销售订单不能为空");
    }
}